package cn.ciis.sys.menu;

import cn.ciis.basic.auth.AdminAuthService;
import cn.ciis.basic.base.BaseService;
import cn.ciis.basic.model.Menu;
import cn.ciis.basic.model.Taxonomy;
import com.jfinal.aop.Aop;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 冉志林
 */
public class MenuAdminService extends BaseService {

    private Menu dao = new Menu().dao();
    private Taxonomy taxonomyDao = new Taxonomy().dao();
    static AdminAuthService adminAuthSrv = Aop.get(AdminAuthService.class);


    @Override
    public Model getDao() {
    return dao;
  }

    public List<Menu> listSuperior(Integer id) {
        String sql =
                "SELECT  id  ,`name`  ,(select count(a.id) from sys_menu a where a.superior=sys_menu.id)as superiorCount ,serialNumber  ,url FROM sys_menu where superior=0";
        if (null != id) {
            sql += " and id <> " + id;
        }
        return dao.find(sql);
    }

    public List<Record> getAllMenu() {
        return Db.find(
                "SELECT  id  ,`name`  ,(select a.`name` from sys_menu a where a.id=sys_menu.superior) as superiorName ,serialNumber  ,(select a.`icon` from sys_menu a where a.id=sys_menu.superior) as superiorIcon ,url,icon FROM sys_menu where superior <> 0  ORDER BY id ASC");
    }

    /**
     * 查询模块信息
     *
     * @param taxId
     * @return
     */
    public List<Record> findByTaxMenu(int taxId) {
        return Db.find(
                "select id,`name`,serialNumber from sys_menu WHERE taxId=? AND state = 0 and status =1 ", taxId);
    }

    public Map<String, List<Record>> groutBySuperior(List<Record> menuList, int loginAccountId) {
        Map<String, List<Record>> map = new LinkedHashMap<>();
        for (Record record : menuList) {
            int state = record.getInt("state");
            boolean superAdmin = adminAuthSrv.isSuperAdmin(loginAccountId);
            String url = record.get("url");
            if (!superAdmin && !url.equals("/") && !adminAuthSrv.hasPermission(loginAccountId, url)) {
                continue;
            } else {
                // 存在子菜单
                if (0 == record.getInt("superior")) {
                    List<Record> recordList = getChild(record.getInt("id"));
                    if (!recordList.isEmpty()) {
                        // 一级菜单名称
                        map.put(record.get("name"), recordList);
                    }
                } else { // 不存在
                    if (record.getInt("superior") == state || record.getInt("superior") == 0) {
                        List<Record> records = new ArrayList<Record>();
                        record.set("superior", 0);
                        records.add(record);
                        map.put(record.get("name"), records);
                    }
                }
            }
        }
        return map;
    }

    public List<Record> getChild(int id) {
        return Db.find(
                "select id,`name`,url,icon,superior,(select a.`icon` from sys_menu a where a.id=sys_menu.superior) as superiorIcon from sys_menu where superior=? and status=1",
                id);
    }

    public List<Taxonomy> taxonomyList() {
        return taxonomyDao.findAll();
    }

    public List<Record> findByMenu(int id) {
        String sql =
                "SELECT id,`name`,superior,serialNumber,url,icon,taxId,state,`status` FROM sys_menu where state=? and status=1 order by serialNumber";
        return Db.find(sql, id);
    }

    public List<Record> findByMenu(int id, int superior) {
        return Db.find(
                "SELECT id,`name`,superior,serialNumber,url,icon,taxId,state FROM sys_menu where state=?  and superior=? and status=1",
                id,
                superior);
    }

    /**
     * 获取模块最大编号加1
     *
     * @param taxId
     * @return
     */
    public Menu findMaxSerial(String taxId) {
        return dao.findFirst(
                "SELECT (CASE WHEN max(serialNumber) IS NULL THEN 1 ELSE max(serialNumber)+1 end) as maxSerial FROM `sys_menu` where taxId=? and state=0",
                taxId);
    }

    public Menu findMaxMenuSerial(String taxId, String modelId, String menuId) {
        Menu menu = null;
        String sql =
                "SELECT (CASE WHEN max(serialNumber) IS NULL THEN 1 ELSE max(serialNumber)+1 end)  as maxSerial FROM `sys_menu` where taxId=? and  state=?";
        if ("0".equals(menuId)) {
            // 一级菜单
            //sql += " and superior=0";
            menu = dao.findFirst(sql, taxId, modelId);
        } else {
            if (StrKit.notBlank(modelId) && !modelId.equals(menuId)) {
                sql += " and superior=?";
            } else {
                sql += " and (superior=? or superior = 0)";
            }
            menu = dao.findFirst(sql, taxId, modelId, menuId);
        }
        return menu;
    }

    public List<Menu> findModel(String taxId) {
        return dao.find("select id,`name` from sys_menu where taxId=? and  superior = -1", taxId);
    }

    public List<Menu> findMenu(String taxId, String modelId) {
        return dao.find("select id,`name`,url,icon,(case `status` WHEN 0 THEN '停用' else '启用' end)`status` from sys_menu where taxId=? and  state = ? ORDER BY serialNumber ASC", taxId, modelId);
    }
}
